package cn.stylefeng.guns.modular.family.controller;

import cn.stylefeng.guns.core.common.annotion.Permission;
import cn.stylefeng.guns.core.common.constant.factory.PageFactory;
import cn.stylefeng.guns.core.common.page.PageInfoBT;
import cn.stylefeng.guns.core.shiro.ShiroKit;
import cn.stylefeng.guns.core.shiro.ShiroUser;
import cn.stylefeng.guns.modular.classification.service.IClassificationService;
import cn.stylefeng.guns.modular.familynum.service.IFamilynumService;
import cn.stylefeng.guns.modular.system.model.*;
import cn.stylefeng.guns.modular.system.service.IUserService;
import cn.stylefeng.guns.modular.system.warpper.FamilyWarpper;
import cn.stylefeng.roses.core.base.controller.BaseController;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.beans.factory.annotation.Autowired;
import cn.stylefeng.guns.core.log.LogObjectHolder;
import org.springframework.web.bind.annotation.RequestParam;
import cn.stylefeng.guns.modular.family.service.IFamilyService;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * 家庭表控制器
 *
 * @author fengshuonan
 * @Date 2021-04-12 10:48:11
 */
@Controller
@RequestMapping("/family")
public class FamilyController extends BaseController {

    private String PREFIX = "/family/family/";

    private String guanliyuan="1";

    private String huzhu="5";

    private String jiatingchengyuan="6";

    private String yonghu="7";

    @Autowired
    private IFamilyService familyService;

    @Autowired
    private IClassificationService classificationService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IFamilynumService familynumService;

    /**
     * 跳转到家庭表首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "family.html";
    }

    /**
     * 跳转到添加家庭表
     */
    @RequestMapping("/family_add")
    public String familyAdd(Model model) {
        EntityWrapper<Classification> wrapper=new EntityWrapper<>();
        wrapper.eq("pcode","jtlx");

        List<Classification> classifications=classificationService.selectList(wrapper);
        model.addAttribute("classifications",classifications);

        Integer createid= ShiroKit.getUser().getId();
        model.addAttribute("createid",createid);

        return PREFIX + "family_add.html";
    }

    /**
     * 跳转到修改家庭表
     */
    @RequestMapping("/family_update/{familyId}")
    public String familyUpdate(@PathVariable Integer familyId, Model model) {

        EntityWrapper<Classification> wrapper=new EntityWrapper<>();
        wrapper.eq("pcode","jtlx");
        List<Classification> classifications=classificationService.selectList(wrapper);
        model.addAttribute("classifications",classifications);

        Family family = familyService.selectById(familyId);
        model.addAttribute("item",family);
        LogObjectHolder.me().set(family);
        return PREFIX + "family_edit.html";
    }

    /**
     * 获取家庭表列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    @Permission
    public Object list(String condition) {

//        return familyService.selectList(null);
        Page<Map<String,Object>> page=new PageFactory<Map<String,Object>>().defaultPage();
        EntityWrapper<Family> familyEntityWrapper=new EntityWrapper<>();

        familyEntityWrapper.orderBy("id",false);

        Integer userid=ShiroKit.getUser().getId(); //用户id
        String roleid=userService.selectById(userid).getRoleid();//当前用户的角色id

        if(roleid.equals(guanliyuan)){ //超级管理员

        }
        else if(roleid.equals(yonghu)){

        }
        else{ //户主和普通家庭成员
            Integer familyid=userService.selectById(userid).getVersion();//当前用户的家庭id
//          Integer familyheadid=familyService.selectById(familyid).getCreateid();//户主的id

            familyEntityWrapper.eq("id",familyid);
        }

        Page<Map<String,Object>>mapPage=familyService.selectMapsPage(page,familyEntityWrapper);
        page=new FamilyWarpper(mapPage).wrap();
        return new PageInfoBT<>(page);
    }

    /**
     * 新增家庭表  创建家庭
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(Family family) {
        //加入家庭
        family.setCreatetime(new Date());

        Integer userid=ShiroKit.getUser().getId(); //当前用户
        Integer a=getFamilyid(userid);

        if(getFamilyid(userid)!=-1){

            Store store=new Store();
            store.setV1("error");
            return store;
        }
        else{
            familyService.insert(family);
        }

//        familyService.insert(family);

        EntityWrapper<Family> familyEntityWrapper=new EntityWrapper<>();
        familyEntityWrapper.eq("createid",userid);
        Family f=familyService.selectOne(familyEntityWrapper);


        //在家庭成员表中加入一条记录
        Familynum familynum = new Familynum();
        familynum.setFamilyid(family.getId());
        familynum.setFamilykindid(family.getFamilykindid());
        familynum.setFamilyname(family.getSpare1());
        familynum.setFamilyheadid(family.getCreateid());
        familynum.setFamilyuserid(family.getCreateid());
        familynum.setJointime(family.getCreatetime());

        familynumService.insert(familynum);

        //更新用户的家庭id user.version
        User user=userService.selectById(userid);
        user.setVersion(f.getId());

        //更新用户的角色Roleid
        if(user.getRoleid().equals(yonghu)){
            user.setRoleid(huzhu);
        }
        System.out.println("***"+user.getRoleid()+"****");
        userService.updateById(user);

        return SUCCESS_TIP;
    }

    /**
     * 删除家庭表
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Integer familyId) {
        EntityWrapper<Familynum> familynumEntityWrapper=new EntityWrapper<>();
        familynumEntityWrapper.eq("familyid",familyId);
        List<Familynum> familynumList=familynumService.selectList(familynumEntityWrapper);

        List<Integer> useridList=new LinkedList<>();  //家庭成员中的用户id

        //删除对应的家庭成员 重新设置角色为用户，
        for(int i=0;i<familynumList.size();i++){
            Integer familynumid=familynumList.get(i).getId(); //家庭成员id
            familynumService.deleteById(familynumid);

            useridList.add(familynumid);
        }

        //重新设置角色为用户 清除sys_user表中的version字段
        for(int i=0;i<useridList.size();i++){
            User user=userService.selectById(useridList.get(i));
            user.setRoleid(yonghu);
            user.setVersion(null);

            userService.updateById(user);
        }


        //删除家庭
        familyService.deleteById(familyId);
        return SUCCESS_TIP;
    }

    /**
     * 修改家庭表
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(Family family) {
        family.setUpdatetime(new Date());
        Integer userid=ShiroKit.getUser().getId();
        family.setUpdateid(userid);

        familyService.updateById(family);
        return SUCCESS_TIP;
    }

    /**
     * 家庭表详情
     */
    @RequestMapping(value = "/detail/{familyId}")
    @ResponseBody
    public Object detail(@PathVariable("familyId") Integer familyId) {
        return familyService.selectById(familyId);
    }


    public Integer getFamilyid(Integer userid){
        EntityWrapper<Familynum> familynumEntityWrapper1=new EntityWrapper<>();
        familynumEntityWrapper1.eq("familyuserid",userid);
        Familynum familynum=familynumService.selectOne(familynumEntityWrapper1);


        //判断是否为空时不能够用 .equals(null)
        if(familynum==null){
            return -1;
        }
        else{
            return familynum.getFamilyid();
        }
    }



}
